package eScrum.components;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.util.string.AppendingStringBuffer;


public class MWindow  extends ModalWindow{
	private static final long serialVersionUID = 1L;

	private ModalWindow closeThisWhenClose;

	public MWindow(String id, Panel panel) {
		super(id);

		init();

		this.setContent(panel);
	}

	public MWindow(String id, ModalWindow closeThisWhenClose) {
		super(id);

		this.closeThisWhenClose = closeThisWhenClose;

		init();
	}

	public MWindow(String id) {
		super(id);

		init();
	}

	public void setDimensions() {
		this.setInitialHeight(430);
		this.setInitialWidth(780);
		this.setMinimalHeight(430);
		this.setMinimalWidth(780);
	}

	private void init() {
		setDimensions();
		this.add(new CenterWindowOnScreenBehavior());

		this.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
			private static final long serialVersionUID = 1L;

			public void onClose(AjaxRequestTarget target) {
				if (closeThisWhenClose != null) {
					closeThisWhenClose.close(target);
				}

				onWindowClose(target);
			}
		});
		this.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() {
			private static final long serialVersionUID = 1L;

			public boolean onCloseButtonClicked(AjaxRequestTarget target) {
				return true;
			}
		});
	}

	public void onWindowClose(AjaxRequestTarget target) {
	}

	public void show(final AjaxRequestTarget target) {
		if (!isShown()) {
			final AppendingStringBuffer buffer = new AppendingStringBuffer(500);

			buffer.append("function mwClose(ev) {\n" +

			"var code = ev.keyCode || ev.which;\n" +

			"if (code == 27) { " +

			getCloseJavacript() +

			"};" +

			"}");

			buffer.append("jQuery(document).keypress(mwClose);\n");

			target.appendJavaScript(buffer.toString());
		}
		// target.prependJavaScript("Wicket.Window.unloadConfirmation = false;");
		// target.appendJavaScript("Wicket.Window.unloadConfirmation = false;");
		super.show(target);
	}

	@Override
	public void renderHead(IHeaderResponse response) {
		super.renderHead(response);
		response.renderOnDomReadyJavaScript("try{Wicket.Window.unloadConfirmation = false;}catch(exception){}");
	}
}
